package com.lanou3g.springmvc.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/**
 * 使用apache fileupload实现文件上传
 */
@Controller
@RequestMapping("/standard")
public class StandardServletFileUploadController {

    /**
     * 使用Servlet3.0 SpringMVCAPI上传
     * @param file
     * @param req
     * @param model
     * @return
     */
    @RequestMapping("/upload")
    public String upload(@RequestParam("myFile") MultipartFile file, HttpServletRequest req, Model model) {
        try {
            file.transferTo(new File(WebUtils.getRealPath(req.getServletContext(), "/upload/")+file.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        StringBuilder sb = new StringBuilder();
        sb.append("http://localhost:8080/upload/");
        sb.append(file.getOriginalFilename());

        model.addAttribute("filePath", sb.toString());
        model.addAttribute("fileName", file.getOriginalFilename());

        return "filelist";
    }


    /**
     * 使用Servlet3.0原生API上传
     * @param req
     * @param model
     * @return
     */
    @RequestMapping("/origin_upload")
    public String upload(HttpServletRequest req, Model model) {

        Part part = null;
        try {
            part = req.getPart("myFile");
            part.write(new File(WebUtils.getRealPath(req.getServletContext(), "/upload/"+part.getSubmittedFileName())).getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }
        StringBuilder sb = new StringBuilder();
        if(part != null) {
            sb.append("http://localhost:8080/upload/");
            sb.append(part.getSubmittedFileName());

            model.addAttribute("filePath", sb.toString());
            model.addAttribute("fileName", part.getSubmittedFileName());
        }
        return "filelist";
    }


}
